package cn.diancan.util.images;

import java.io.File;
import java.util.UUID;

import cn.diancan.util.CompressImg;
import cn.diancan.util.HttpClientUtil;

 

public class UploadImageUtil {
    
    public static String uploadHost="http://img.zuwo.la/YmUpload_image";
    
    public static String basePath =null;
    
    public static void main(String[] args) {
	try {
	    String s=getNewImageUrl("http://q.qlogo.cn/qqapp/1104574025/389F870E5B75C311E7C6B041A2CC8FA7/100");
	    System.out.println(s);
	} catch (Exception e) { 
	    e.printStackTrace();
	}
    }
    
    public static String getNewImageUrl(String imgUrl) throws Exception{
	File file =null;
	File file2 =null;
	try {
	    if(null == basePath){ 
	        String tempSrc = Class.forName(UploadImageUtil.class.getName()).getResource("/").getPath();
	    	basePath = tempSrc.substring(0, tempSrc.length()-"WEB-INF/classes/".length())+"uploadTemp/"; 
	    	//basePath ="D:/ProgramFiles/apache-tomcat-6.0.36/webapps/zuwo/uploadTemp/";
	    }
	    String suffix=".jpg";
	    String fileName = basePath+UUID.randomUUID().toString()+suffix;
	    file =new File(fileName);
	    while(file.exists()){//直到找到不存在的 
	            fileName= basePath+UUID.randomUUID().toString()+suffix;
	            file = new File(fileName);
	    }
	    
	    file = HttpClientUtil.getFilebyUrl2(imgUrl,fileName, false);
	    if(null == file){
	    	return null;
	    }
	    
	    //图片压缩
	    if(file.length()>40960){
	    	file2 =  new File(file.getPath()); 
	    	CompressImg.compressPic(file2.getPath(), file.getPath(), null, null, false);
	    }
	    
	    String image = HttpClientUtil.uploadFile(uploadHost, file, "file");  
	    return image;
	} catch (Exception e) { 
	    e.printStackTrace();
	} finally {
	    if (null != file) {// 删除图片保证磁盘有足够空间
		try {
		    file.delete();
		} catch (Exception e) {
		    System.out.println(e.getMessage());
		}
	    }
	    if (null != file2) {
		try {
		    file2.delete();
		} catch (Exception e) {
		    System.out.println(e.getMessage());
		}
	    }
	}
	return null;
    }
    
    
    
    
    
}
